<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;
use app\api\model\User;


class Collect extends Model
{
    // 设置表名
    protected $name = 'collect';
    
    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 软删除
    protected $deleteTime = 'delete_time';

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 关联图片具体信息
     */
    public function mainImage()
    {
        return $this->belongsTo('app\api\model\OssFile', 'img_id', 'id');
    }

    /**
     * 添加收藏
     * @param int $userId
     * @param int $groupId
     * @return bool
     */
    public static function addCollect(int $userId, int $groupId): bool
    {
        // 检查是否已收藏
        $exist = self::where([
            ['user_id', '=', $userId],
            ['img_id', '=', $groupId],
            ['delete_time', '=', null]
        ])->find();

        if ($exist) {
            return true;
        }

        // 添加收藏
        return (new self([
            'user_id' => $userId,
            'img_id' => $groupId
        ]))->save();
    }

    /**
     * 取消收藏
     * @param int $userId
     * @param int $groupId
     * @return bool
     */
    public static function cancelCollect(int $userId, int $groupId): bool
    {
        $result = self::where([
            ['user_id', '=', $userId],
            ['img_id', '=', $groupId]
        ])->update(['delete_time' => time()]);
        
        return $result !== false;
    }

    /**
     * 检查是否已收藏
     * @param int $userId
     * @param int $groupId
     * @return bool
     */
    public static function isCollected(int $userId, int $groupId): bool
    {
        return self::where([
            ['user_id', '=', $userId],
            ['img_id', '=', $groupId],
            ['delete_time', '=', null]
        ])->count() > 0;
    }

    /**
     * 获取收藏列表
     * @param int $userId
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList(int $userId=0, int $page = 1, int $limit = 10): array
    {
        $query = self::with(['mainImage' => function($query) {
                    $query->field('id,file_url');
                }])->whereNull('delete_time')->order('create_time', 'desc');
        if ($userId){
            $query = $query->where('user_id', $userId);
        }
        $total = $query->count();
        $list = $query->page($page, $limit)->select()->toArray();
;
        $data = [];
        foreach ($list as $item) {
            if ($item['mainImage']) {
                if($item['mainImage']['file_url'] && strpos($item['mainImage']['file_url'], 'http') === false){
                    $item['mainImage']['file_url'] = env('OSS_DOMAIN', '') . $item['mainImage']['file_url'];
                }
                $image_url = $item['mainImage']['file_url'];
            }
            $data[] = [
                'collect_id' => $item['id'],
                'img_id' => $item['img_id'],
                //'name' => $item->productGroup->name,
                'image_url' => $image_url,
                'create_time' => $item['create_time']
            ];

        }

        return [
            'total' => $total,
            'list' => $data,
            'page' => $page,
            'limit' => $limit
        ];
    }
} 